package top.lilele.adminSystem.web;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;
import top.lilele.adminSystem.dto.OnlineUserDto;
import top.lilele.adminSystem.entity.AdminUserEntity;
import top.lilele.adminSystem.handler.WebSocketHandler;
import top.lilele.adminSystem.mapper.AdminUserMapper;
import top.lilele.adminSystem.utils.BaseResponse;
import top.lilele.adminSystem.utils.ResponseCodeEnum;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author lilele
 */
@RestController
@RequestMapping(value = "onlineUser")
@Slf4j
public class OnLineUserController {

    @Resource
    AdminUserMapper adminUserMapper;

    @PostMapping(value = "query")
    public BaseResponse query() {
        ConcurrentHashMap<String, WebSocketSession> onLineUserList = WebSocketHandler.getOnLineUserList();
        List<AdminUserEntity> allUserList = adminUserMapper.selectList(null);
        List<OnlineUserDto> onlineUsers = new ArrayList<>();
        onLineUserList.forEach((key, value) -> {
            String userId = (String) StpUtil.getLoginIdByToken(key);
            OnlineUserDto onlineUserDto = new OnlineUserDto();
            onlineUserDto.setSessionId(value.getId());
            List<AdminUserEntity> filterList = allUserList.stream().filter(item -> item.getId().equals(userId)).collect(Collectors.toList());
            onlineUserDto.setUserId(filterList.get(0).getId());
            onlineUserDto.setTrueName(filterList.get(0).getTrueName());
            onlineUsers.add(onlineUserDto);
        });
        return BaseResponse.info(ResponseCodeEnum.Success, onlineUsers);
    }
}
